<template>
  <div class="top_bar">
    <div class="left_con">
      <div class="head_icon">
        <img
          src="@/common/image/workShotstackImage/shotstack_white_logo.png"
          alt=""
        />
      </div>
	  
	  <div class="edit_model">
		  <img style="width: 35px; height: 35px;" :src="editModelObj?.edit_model_image" alt="" />
		  {{editModelObj?.edit_model_name}}
	  </div>
	  
      <div class="back_con" @click="backPrevious" v-if="showBack">
        <cu-icon
          class="icon"
          type="icon-fanhui"
          style="font-size: 16px; cursor: pointer"
        />
        <div class="back_txt">返回</div>
      </div>
    </div>

    <div class="right_operate" v-if="showSave">
      <a-button
        :loading="currentType == 'save' && loading"
        class="btn_style"
        ghost
        size="default"
        style="border: 1px solid #999"
        @click="saveOnly()"
      >
        <template #icon>
          <CloudUploadOutlined />
        </template>
        仅保存
      </a-button>

      <a-button
        class="btn_style"
        :loading="currentType == 'saveAndGo' && loading"
        type="primary"
        ghost
        size="default"
        style="
          margin-left: 20px;
          background-color: #2878FF;
          color: #fff;
          border: 0;
        "
        @click="saveAndGo()"
      >
        <template #icon>
          <FileDoneOutlined />
        </template>
        保存并前往生成
      </a-button>
    </div>
  </div>

  <a-modal
    class="generate-modal"
    :width="420"
    :visible="loadingVisible"
    :bodyStyle="{ padding: 0 }"
    :footer="null"
    :closeIcon="null"
  >
    <div class="content">
      <img :src="PlayLoading" />
      <div>正在生成</div>
      <div>大概需要1～3分钟</div>
      <div>你可以继续在此页面等待或稍后重新进入剪辑任务查看</div>
      <a-button
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          border-color: rgba(255, 255, 255, 0.24);
          padding: 20px 30px;
          border-radius: 6px;
        "
        type="default"
        ghost
        @click="handleGo"
        >稍后查看</a-button
      >
    </div>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  createVNode,
  ref,
  nextTick,
  h,
} from "vue";
import {
  RightOutlined,
  LeftOutlined,
  RollbackOutlined,
  CloudUploadOutlined,
  FileDoneOutlined,
} from "@ant-design/icons-vue";
import PlayLoading from "./static/play-loading.gif";
import store from "@/store";
import request from "../../../../../common/utils/request";
import { Modal, message } from "ant-design-vue";
import { sumBy, minBy, maxBy } from "lodash";
import { useRouter, useRoute } from "vue-router";
import { useTimeoutPoll } from "@vueuse/core";
export default defineComponent({
  emits: ["backPrevious"],
  props: {
    showSave: {
      type: Boolean,
      default: false,
    },
    showBack: {
      type: Boolean,
      default: true,
    },
  },
  components: {
    RollbackOutlined,
    CloudUploadOutlined,
    FileDoneOutlined,
  },
  setup(props, context) {
    const router = useRouter();
    const route = useRoute();
    const systemLogo = computed(
      () => store.getters?.configInfo?.basic?.system_logo
    );

    const state = reactive({
      scrollAmount: 0,
      loading: false,
      currentType: "",
      loadingVisible: false,
    });

    const backPrevious = () => {
      context.emit("backPrevious");
    };
	const editModelObj = computed(()=> {
		let edit_model = store.getters.clipJSON.edit_model
		let edit_model_name = ''
		let edit_model_image = ''
		if(edit_model == 1) {
			edit_model_name = '智能剪辑';
			edit_model_image = new URL('../../../../../common/image/workShotstackImage/img_znjj.png', import.meta.url).href;
		}
		if(edit_model == 2) {
			edit_model_name = '一键剪辑';
			edit_model_image = new URL('../../../../../common/image/workShotstackImage/img_yjcp.png', import.meta.url).href;
		}
		if(edit_model == 3) {
			edit_model_name = '模板剪辑';
			edit_model_image = new URL('../../../../../common/image/workShotstackImage/img_ksjj.png', import.meta.url).href;
		}
		if(edit_model == 4) {
			edit_model_name = '脚本剪辑';
			edit_model_image = new URL('../../../../../common/image/workShotstackImage/img_jbjj.png', import.meta.url).href;
		}
		if(edit_model == 5) {
			edit_model_name = '图文剪辑';
			edit_model_image = new URL('../../../../../common/image/workShotstackImage/img_twjj.png', import.meta.url).href;
		}
		return {
			edit_model_name,
			edit_model_image
		}
	})

    const getGeneratePreview = () => {
      request
        .get("work_ai", "/user/shotstack/clip/response/list", {
          editing_record_id: store.getters.clipJSON.id,
          edit_model: store.getters.clipJSON.edit_model,
        })
        .then((res) => {
          if (res?.result?.some((item) => item.status === "done")) {
            router.push({
              name: "EditingCenterPreview",
              query: {
                id: store.getters.clipJSON.id,
                edit_model: store.getters.clipJSON.edit_model,
              },
            });
            state.loadingVisible = false;
            pause();
          } else if (store.getters.clipJSON.edit_model == 5) {
            router.push({
              name: "EditingCenterPreview",
              query: {
                id: store.getters.clipJSON.id,
                edit_model: store.getters.clipJSON.edit_model,
              },
            });
            state.loadingVisible = false;
            pause();
          }
          return;
          if (res?.result) {
            router.push({
              name: "EditingCenterPreview",
              query: {
                id: store.getters.clipJSON.id,
                edit_model: store.getters.clipJSON.edit_model,
              },
            });
            state.loadingVisible = false;
            message.success("操作成功");
            pause();
          }
        })
        .catch(() => {
          state.loading = false;
          state.loadingVisible = false;
          pause();
        });
    };

    const handleGo = () => {
      state.loadingVisible = false;
      router.push({
        name: "IntelligentClipping",
      });
    };

    const { pause, resume } = useTimeoutPoll(getGeneratePreview, 3000);

    const postRequest = () => {
      if (store?.getters?.clipJSON?.edit_model == 2) {
        state.loadingVisible = true;
      }
      // edit_model === 2 一键成片
      let postUrl = "";
      if (store?.getters?.clipJSON?.edit_model == 2) {
        //一键成片
        postUrl = "/user/shotstack/clip/oneclik/preview";
      } else if (store?.getters?.clipJSON?.edit_model == 3) {
        //模板剪辑
        postUrl = "/user/shotstack/clip/template/preview";
      } else if (store?.getters?.clipJSON?.edit_model == 5) {
        //图文剪辑
        postUrl = "/user/shotstack/clip/image_text";
      } else {
        postUrl = "/user/shotstack/clip/samrt/preview";
      }
      request
        .post("work_ai", postUrl, {
          ...store.getters.clipJSON,
          resource_data: store.getters.clipJSON.resource_data.map(
            (item, index) => ({
              ...item,
              sn: index + 1,
            })
          ),
          save: 1,
        })
        .then((res) => {
          setTimeout(() => {
            router.push({
              name: "EditingCenterPreview",
              query: {
                id: store.getters.clipJSON.id,
                edit_model: store.getters.clipJSON.edit_model,
                comeFrom:route.query.comeFrom !== 'undefined' ? route.query.comeFrom : 'Home'
              },
            });
            state.loadingVisible = false;
          }, 1000);
        })
        .catch(() => {
          state.loadingVisible = false;
          state.loading = false;
        });
    };

    const saveOnly = () => {
      state.currentType = "save";

      if (
        store.getters.clipJSON.resource_data?.find((i) => i.video?.length === 0)
      ) {
        message.error("没有素材，请先选择或拖入素材");
        state.loading = false;
        return;
      }
      request
        .post("work_ai", "/user/shotstack/clip/samrt/saveonly", {
          ...store.getters.clipJSON,
          resource_data: store.getters.clipJSON.resource_data.map(
            (item, index) => ({
              ...item,
              sn: index + 1,
            })
          ),
          save: 1,
        })
        .then((res) => {
          state.loading = false;
          backPrevious();
          message.success("操作成功");
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const saveAndGo = () => {
      state.currentType = "saveAndGo";
      state.loading = true;

      // if (store.state.shotstack?.generateLoading) {
      //   message.warning("还有视频未生成，请耐心等待");
      //   state.loading = false;
      //   return;
      // }

      // 一键成片
      if (store.getters.clipJSON.edit_model == 2) {
        if (!store.getters.clipJSON?.ai_compose_config?.ai_data?.content) {
          message.warning("请输入视频大纲");
          state.loading = false;
          return;
        }
        if (
          store.getters.clipJSON?.ai_compose_config?.num >= 1 &&
          store.getters.clipJSON?.ai_compose_config?.num < 10 &&
          store.getters.clipJSON?.resource_data?.[0]?.video?.length < 5
        ) {
          message.warning("素材数量不低于5个");
          state.loading = false;
          return;
        }

        if (
          store.getters.clipJSON?.ai_compose_config?.num >= 10 &&
          store.getters.clipJSON?.resource_data?.[0]?.video?.length < 10
        ) {
          message.warning("素材数量不低于10个");
          state.loading = false;
          return;
        }
      }

      if (
        store.getters.clipJSON.edit_model != 5 &&
        store.getters.clipJSON.resource_data?.find((i) => i.video?.length === 0)
      ) {
        message.error("没有素材，请先选择或拖入素材");
        state.loading = false;
        return;
      }

      // 图文剪辑
      if (
        store.getters.clipJSON.edit_model == 5 &&
        store.getters.clipJSON.resource_data?.find(
          (i) => i.images?.length === 0
        )
      ) {
        message.error("没有素材，请先选择或拖入素材");
        state.loading = false;
        return;
      }

      const {
        expectedVideo,
        clipJSON: { audio },
      } = store.getters;
      // 视频静音提示
      if (
        store.getters.clipJSON.edit_model != 5 &&
        expectedVideo?.isVideoMute === true
      ) {
        return Modal.confirm({
          title: "提示",
          content:
            "你将要合成的视频中未添加或开启任何声音，确定还要继续合成吗？",
          okText: "确定",
          cancelText: "取消",
          onOk: () => {
            postRequest();
          },
          onCancel: () => {
            state.loading = false;
          },
        });
      }

      // 口播时长最大的那一个与视频时长最小值对比 如果大于视频最小值则提示
      if (store.getters.clipJSON.edit_model != 5 && audio?.length > 0) {
        const _maxTime = maxBy(audio, "material_duration").material_duration;
        if (_maxTime > expectedVideo?.videoTime) {
          return Modal.confirm({
            title: "解说音频大于成片时长",
            content: h("div", {}, [
              h(
                "div",
                "有解说音频时长大于成片预计时长，可能导致合成效果较差，你确定还要继续吗？"
              ),
              h("div", "温馨提示：建议更换较短的解说音频"),
            ]),
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
              postRequest();
            },
            onCancel: () => {
              state.loading = false;
            },
          });
        }
      }

      postRequest();
    };

    return {
      backPrevious,
      saveAndGo,
      saveOnly,
      systemLogo,
      ...toRefs(state),
      PlayLoading,
      handleGo,
	  editModelObj
    };
  },
});
</script>

<style lang="less">
.top_bar {
  width: 100%;
  height: 60px;
}
.generate-modal {
  .ss-modal-content {
    background: rgb(44, 44, 50);
    padding: 28px 40px;
  }
  .ss-modal-close {
    display: none;
  }

  .content {
    padding: 30px 0;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    gap: 8px 12px;

    img {
      width: 120px;
      height: 120px;
    }

    > div:nth-child(2) {
      font-size: 22px;
      color: #fff;
    }

    > div:nth-child(3) {
      margin-top: 12px;
      color: #888;
      font-size: 12px;
    }
    > div:nth-child(4) {
      margin-bottom: 20px;
      color: #888;
      font-size: 12px;
    }
  }
}
</style>

<style lang="less" scoped>
.top_bar {
  background-color: #131313;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  border-bottom: 1px solid #000;

  .left_con {
    display: flex;
    align-items: center;

    .head_icon {
      display: flex;
      align-items: center;

      .head_text {
        color: #fff;
        font-size: 24px;
        margin-left: 5px;
      }

      img {
        height: 34px;
      }
    }
	
	.edit_model{
		color: #ddd;
		font-size: 17px;
		margin-left: 30px;
	}

    .back_con {
      display: flex;
      align-items: center;
      color: #ddd;
      margin-left: 30px;
      cursor: pointer;
      padding: 3px 10px;

      &:hover {
        background: rgba(255, 255, 255, 0.2);
        border-radius: 5px;
      }

      .back_txt {
        font-size: 15px;
        transform: translateY(1px);
        margin-left: 5px;
      }
    }
  }

  .right_operate {
    display: flex;
    align-items: center;
    .btn_style {
      border-radius: 5px;
      color: #fff;
    }
  }
}
</style>
